import random
from datetime import datetime, timedelta

from flask import Flask,session
from flask import current_app

from info import create_app,db,models
from flask_migrate import Migrate,MigrateCommand
from flask_script import Manager

from info.models import User

app = create_app("develop")

manager = Manager(app)

Migrate(app,db)

manager.add_command("db",MigrateCommand)

#创建管理方法，通过flask_script模块提供的option装饰器

#参数1：表示传递的值　参数2：解释参数１　参数３：dest目标值用来传递形参的
@manager.option('-u', '--username', dest='username')
@manager.option('-p', '--password', dest='password')
def create_superuser(username,password):
    #1.创建管理员用户
    admin = User()

    #2.设置属性
    admin.nick_name = username
    admin.mobile = username
    admin.password = password
    admin.is_admin = True

    #3.保存到数据库
    try:
        db.session.add(admin)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return "创建失败"
    return "创建成功"

# 为了查看图表方便，添加测试用户
@manager.option('-t', '--test', dest='test')
def add_test_user(test):

    #定义用户容器
    user_list = []

    #创建测试用户，设置属性
    for i in range(0,1000):
        user = User()
        user.mobile = "138%08d"%i
        user.nick_name = "老王%d"%i
        user.password_hash = "pbkdf2:sha256:50000$smZUMDIJ$b9523a52c44a0519a346d3b478ab523d6af64e2907e6821da55f26b093a70796"

        #最近31天以来登陆时间
        user.last_login = datetime.now()-timedelta(seconds=random.randint(0,3600*24*31))
        user_list.append(user)

    #添加数据库
    try:
        db.session.add_all(user_list)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return "创建失败"

    return "创建成功"
if __name__ == '__main__':
    manager.run()